<?php
namespace app\admin\controller;

use think\App;
use think\facade\View;

use app\BaseController;
use app\admin\model\SysUser as SysUserModel;
use app\admin\model\SysLogin as LoginModel;

class Login extends BaseController
{
    protected $user_model;

    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $this->user_model = new SysUserModel();
    }

    public function index()
    {
        if ($this->app->request->isPOST()) {
            // var_dump(input('post.'));
            // exit;
            $username = trim(input('post.username'));
            $password = trim(input('post.password'));
            $verify = trim(input('post.verify'));

            if (!$username || !$password || !$verify) {
                $this->error('用户名/密码/验证码不能为空');
            }

            if (!captcha_check($verify)) {
                $this->error('验证码不正确', 'index');
            }

            $info = $this->user_model->getLogInfo($username);

            if (!$info || md5($password.$info->salt) != $info->password) {
                $this->error('用户名/密码不正确', 'index');
            }

            session('last_time', $info->login_time);
            session('last_ip', $info->login_ip);
            
            $info->login_time = time();

            $info->login_ip = $this->app->request->ip();

            if (!$info->save()) {
                $this->error('登陆失败,请稍后重试', 'index');
            }
            
            //记录登陆信息
            @LoginModel::create([
                'userid'=>$info->id,
                'time'=>$info->login_time,
                'ip'=>$info->login_ip
            ]);
            session('uid', $info->id);
            session('username', $info->username);

            $this->success('登入成功', '/admin/index');
        } else {
            if (session('?username')) {
                $this->success('您已登入', '/admin/index');
            } else {
                return View::fetch();
            }
        }
    }

    /**
     * 登出
     */
    public function logout()
    {
        session(null);
        return View::fetch('index');
    }
}
